import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV, VITE_APP_BASE_API, VITE_APP_BASE_URL } = env

  // 环境判断
  const isProduction = VITE_APP_ENV === 'production'
  const apiPrefix = isProduction ? VITE_APP_BASE_API : '/dev-api'
  const targetUrl = isProduction ? VITE_APP_BASE_URL : 'http://localhost:8080'

  return {
    // 部署路径
    base: isProduction ? '/' : '/',

    plugins: createVitePlugins(env, command === 'build'),

    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'),
        '@': path.resolve(__dirname, './src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },

    // 打包配置
    build: {
      sourcemap: false, // 生产环境关闭sourcemap
      outDir: 'dist',
      assetsDir: 'static',
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
      }
    },

    define: {
      'import.meta.env.BASE_URL': JSON.stringify(targetUrl),
    },

    // 开发服务器配置
    server: {
      port: 80,
      host: true,
      open: true,
      proxy: {
        // 动态代理配置
        [apiPrefix]: {
          target: targetUrl,
          changeOrigin: true,
          rewrite: (p) => p.replace(new RegExp(`^${apiPrefix}`), '')
        },
        // springdoc代理
        '^/v3/api-docs/(.*)': {
          target: targetUrl,
          changeOrigin: true,
        }
      }
    },

    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    }
  }
})